﻿using DAEProde.Domain;
using DAEProde.Tasks.ViewModels;
using SharpLite.Domain.DataInterfaces;
using System.Linq;
using System.Collections.Generic;

namespace DAEProde.Tasks
{
    public class MatchCudTasks : BaseEntityCudTasks<Match, EditMatchViewModel>
    {
        private readonly IRepository<MatchDate> _matchDateRepository;
        private readonly IRepository<Team> _teamRepository;

        public MatchCudTasks(IRepository<Match> matchRepository, IRepository<MatchDate> matchDateRepository, IRepository<Team> teamRepository)
            : base(matchRepository) { _matchDateRepository = matchDateRepository; _teamRepository = teamRepository; }

        protected override void TransferFormValuesTo(Match toUpdate, Match fromForm)
        {
            toUpdate.Name = fromForm.Name;
            toUpdate.Date = fromForm.Date;
            toUpdate.MatchDate = fromForm.MatchDate;
            toUpdate.LocalTeam = fromForm.LocalTeam;
            toUpdate.OutTeam = fromForm.OutTeam;
        }

        // Construccion basica del view model que inicializa lista de equipos para el dropdown
        public override EditMatchViewModel CreateEditViewModel()
        {
            var viewModel = base.CreateEditViewModel();

            // Esto sera mostrado por la vista para seleccionar una fecha
            viewModel.AvaileableMatchDates = _matchDateRepository.GetAll().OrderBy(pc => pc.Name);

            // Esto sera mostrado por la vista para seleccionar un equipo
            viewModel.AvaileableTeams = _teamRepository.GetAll().OrderBy(pc => pc.Name);

            return viewModel;
        }

        public EditMatchViewModel CreateViewModel(int tId)
        {
            var viewModel = CreateEditViewModel();

            var matchDate = _matchDateRepository.Get(tId);

            viewModel.AvaileableMatchDates = viewModel.AvaileableMatchDates.Where(x => x.Equals(matchDate));

            var equipos = new List<Team>();

            foreach (var partido in matchDate.Matches)
            {
                equipos.Add(partido.LocalTeam);
                equipos.Add(partido.OutTeam);
            }

            viewModel.AvaileableTeams = viewModel.AvaileableTeams.Where(x => x.Tournaments.Contains(matchDate.Tournament));

            viewModel.AvaileableTeams = viewModel.AvaileableTeams.Except(equipos);

            viewModel.Match = new Match();
            viewModel.Match.MatchDate = matchDate;

            return viewModel;
        }
    }
}
